#include "DKInclude.h"
#include "HelloWorldScene.h"
DKMap::DKMap(int level, CCObject *scene)
{
	this->Actors = new cocos2d::CCArray;
	this->scene = scene;
	switch(level)
	{
	case 1:
	default:
		this->XMap = 12;
		this->YMap = 8;
		int staticActor[8][12] =
		{
			{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0},
			{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0},
			{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0},
			{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0},
			{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
			{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
			{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
			{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
		};
		this->initialize((int **)staticActor);

		this->TheMan = dka(2, 2, 1);
		this->Actors->addObject(this->TheMan);
		this->Actors->addObject(dka(3, 5, 1));

		DKActorLazerMachine *machine = (DKActorLazerMachine *)dka(4, 1, 0);
		machine->direction = DKEventDirection_Up;
		this->Actors->addObject(machine);
		break;
	}

}
DKMap::~DKMap()
{
}

DKMap * DKMap::create(int level, CCObject *scene)
{
	return new DKMap(level, scene);
}

void DKMap::initialize(int **map)
{
	if(map != NULL)
	{
		for(int i=0; i<this->XMap; i++)
			for(int j=0; j<this->YMap; j++)
			{
				this->Actors->addObject(dka(*((int*)map + j * this->XMap + i), i, this->YMap -1 - j));
			}
	}
}

void DKMap::startActors()
{
	CCObject *obj = NULL;
	CCARRAY_FOREACH(this->Actors, obj)
	{
		DKActor *actor = dynamic_cast<DKActor *>(obj);
		switch(actor->actorType)
		{
		case DKActorType_Lazer_Machine:
			((DKActorLazerMachine *)actor)->startMachine(this);
		}
	}
}

void DKMap::ProcessUserInput(CCPoint screenPoint)
{
	DKPoint targetPoint = DKActor::getIndexPoint(screenPoint);
	
		DKEvent *evt = new DKEvent(TheMan, DKEventType_Push, TheMan->location.GetDirection(targetPoint));
		DKAction *action = TheMan->BePushed(evt, this);
}

DKActor * DKMap::GetActorAt(DKPoint point)
{
	CCObject *obj = NULL;
	DKActor *foundItem = NULL;
	int maxZIndex = -1;
	CCARRAY_FOREACH(this->Actors, obj)
	{
		DKActor *actor = dynamic_cast<DKActor *>(obj);
		if(actor->location.IsEqual(point) && actor->zIndex > maxZIndex && actor->isVisible())
		{
			foundItem = actor;
			maxZIndex = actor->zIndex;
		}
	}
	return foundItem;
}

void DKMap::addActor( DKActor *actor )
{
	this->Actors->addObject(actor);
	((HelloWorld *)this->scene)->addActor(actor);
}
